import { Component, ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams, Content, TextInput } from 'ionic-angular';
import { NativeProvider } from '../../providers/native/native';
import { Global } from '../../common/global';
import { BusiProvider } from '../../providers/busi/busi';
import { Input } from '@angular/compiler/src/core';
declare var io;

/**
 * Generated class for the MettingchatPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-mettingchat',
  templateUrl: 'mettingchat.html',
})
export class MettingchatPage {
  @ViewChild(Content) contentPnl: Content;
  @ViewChild("textaream") textaream:TextInput;
  metting: any;
  userinfo: any;
  chatserver: any;
  mettingid: any;
  userid: any;
  socket: any;
  remessage: any;
  messageList: Array<record> = [];
  defaultImagUrl: any;
  message:any;
  constructor(public navCtrl: NavController, public navParams: NavParams, private native: NativeProvider,private busi:BusiProvider) {
    this.userinfo = this.navParams.get("userinfo");
    this.userid = this.userinfo.userid;
    this.metting = this.navParams.get("metting");
    this.mettingid = this.metting.id;
    this.chatserver = localStorage.getItem("mettingaddress");
    this.defaultImagUrl = "./assets/default-user-img.svg";
    this.getUnreamessage();
    this.socketIoInit();
  }
  /**
   * 初始化socketio
   */
  socketIoInit() {
    this.socket = io(this.chatserver, {
      // 'rejectUnauthorized' : false,
      'reconnection': true,
      'reconnectionAttempts': 3,
      // 'reconnectionDelay': 4000,
      // 'reconnectionDelayMax':300000,
      // 'randomizationFactor':0
      // 'timeout':2000
      'path': '/communicate',
      "doubleEncodeUTF8":true,
      query: {
        Authorization: localStorage.getItem(Global.token)
      },
      'transports': ['polling']
    });
    this.socket.on("connect", () => {
    })
    this.socket.on("reconnect_attempt", (data) => {
      if (data == 1) {
        this.native.showLoading("服务器断开，进行第1次重连!");
      }
      else if (data == 2) {
        this.native.hideLoading();
        this.native.showLoading("服务器断开，进行第2次重连!");
      }
      else if (data == 3) {
        this.native.hideLoading();
        this.native.showLoading("服务器断开，进行第3次重连!");
      }

      if (data > 3) {
        this.socket.close();
      }
    });
    this.socket.on("reconnect_error", () => {
    })
    this.socket.on("reconnect_failed", (data) => {
      this.native.hideLoading();
      this.native.showToast("重连失败!")
      this.navCtrl.pop();
    })
    this.socket.on("reconnect", (data) => {
      this.native.hideLoading();
      this.native.showToast("重连成功！");
    })

    this.socket.on(this.mettingid, (data) => {
      localStorage.setItem(Global.lastReadMessateTime,JSON.parse(data).sendtime);
      data = JSON.parse(data);
      let message = {
        message: data.message,
        userid: data.userid,
        name: data.name,
        sendtime: data.sendtime,
        mettingid: data.mettingid
      }
      this.messageList = this.messageList.concat(message);
      setTimeout(() => {
        this.scrollToBottom();
      }, 500);
    })
  }
  ionViewDidLoad() {
    console.log('ionViewDidLoad MettingchatPage');
  }

  ionViewWillUnload() {
    this.socket.off();
  }
  dealfocus(){
    setTimeout(() => {
      this.scrollToBottom();
    }, 500);
  }
  sendMessage() {
    if(this.message == null || this.message.trim()==""){
      return;
    }
    let chatObject = {
      "mettingId": this.mettingid,
      "message": this.message
    }
    this.socket.emit("chat", chatObject);
    this.message ="";
    setTimeout(() => {
      this.scrollToBottom();
      //this.textaream.setFocus();
    }, 300);
  }
  getUnreamessage() {
    let fromdate= localStorage.getItem(Global.lastReadMessateTime);
    if(fromdate == null || fromdate=='undefined') {
      fromdate = "1970-01-01 00:00:00";
    }
    this.busi.getMessages(this.mettingid,fromdate).subscribe(
      data=>{
        this.messageList = this.messageList.concat(data);
      },err=>{

      }
    );
  }

  scrollToBottom() {
    this.contentPnl.scrollToBottom();
  }
}
class record {
  message: string;
  userid: string;
  name: string;
  sendtime: Date;
  mettingid: string;
}
